const Base64 = require('../base64');
const md5 = require('../utils/md5.min.js');
const key = new Base64();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

function result(status,data,msg){
    this.status = status;
    this.data = data || {};
    this.msg = msg;
}
function Register(req,res){
    MongoClient.connect(url,{useNewUrlParser:true},async function(err,db){
        if(err) throw err;
        var dbo = db.db("mongo");
        let reqdata = {
                username:req.body.user || '',
                passwd: req.body.passwd || ''
            };
            for(var i in reqdata){
                if(!reqdata[i]){
                res.send(new result(110,'',i+'未填写！'));
                return
                }
            };
            let text = '';
            for(let i = 0;i<reqdata.username.length;i++){
                text+=(reqdata.username[i]&&reqdata.username[i]+reqdata.passwd[i]&&reqdata.passwd[i])
            }
            let encrypted = key.encode(text).split('').reverse().join('');
            let passwd = encrypted;
            dbo.collection('member').find({username:reqdata.username}).toArray(function(er,re){
                if (er) throw er;
                if(re.length==0){
                    res.send(new result(101,re,'用户不存在'))
                }
                else{
                    if(re[0].passwd==passwd){
                        let token = md5(Math.random().toString(36).substr(2))
                        dbo.collection('token').insertOne(
                            {token:token,uid:re[0].uid,idx:new Date(),userinfo:{
                                "$ref": "member",
                                "$id": re[0]._id
                            }},
                            function(error,succe){
                                if(error) throw error
                                re[0].token = token
                                delete re[0].passwd;
                                delete re[0]._id;
                                res.send(new result(200,re[0],'成功'));
                            }
                        )
                    }else{
                        res.send(new result(102,{},'密码不正确'))
                    }
                }
            })
    })
  }
  module.exports = Register